import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/mrp_bom_odoo_api.dart';
import 'package:flutter_admin/api/odoo/product_productionorder_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/product_productionorder.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/models/odoo/product_template.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/models/odoo/mrp_bom.dart';
import 'package:flutter_admin/pages/odoo/mrp_bom/mrp_bom_edit.dart';
import 'package:flutter_admin/pages/odoo/mrp_bom/mrp_bom_dialog.dart';

class BindBomList extends StatefulWidget {

  ProductProductionorder productionorder;

  BindBomList({required this.productionorder, Key? key}) : super(key: key);

  @override
  _BindBomListState createState() => _BindBomListState();
}

class _BindBomListState extends State<BindBomList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page = PageModel(orders: [OrderItemModel(column: 'create_date',asc: false)]);
  ProductProductionorder productionorder = ProductProductionorder();
  MrpBom mrpBom = MrpBom();
  List<MrpBom> selectedList = [];
  @override
  void initState() {
    productionorder = widget.productionorder;
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 280,
            label: '产品图号',
            value: mrpBom.productCode,
            onSaved: (v) {
              mrpBom.productCode = v;
            },
          ),
          CryInput(
            width: 280,
            label: '产品名称',
            value: mrpBom.productName,
            onSaved: (v) {
              mrpBom.productName = v;
            },
          ),
        ],
      ),
    );
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map<String,dynamic> selected) {
        this.setState(() {});
      },
      columns: [
	        DataColumn(
          label: Text('产品图号'),
        ),
	        DataColumn(
          label: Text('产品名称'),
        ),
	        DataColumn(
          label: Text('规格型号'),
        ),
	        DataColumn(
          label: Text('计量单位'),
        ),
      ],
      getCells: (m) {
        MrpBom mrpBom = MrpBom.fromMap(m);
        return [
          DataCell(Text(mrpBom.productCode ?? '--')),
          DataCell(Text(mrpBom.productName ?? '--')),
          DataCell(Text(mrpBom.spec ?? '--')),
          DataCell(Text(mrpBom.uomName ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
            label: '确定',
            iconData: Icons.save,
            onPressed: selectedList.length == 1
                ? () => _save(selectedList[0])
                : null),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ScaffoldState? scaffold = Scaffold
                .maybeOf(context);
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('订单绑定BOM清单'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context)?form:Container(),
          isDisplayDesktop(context)?buttonBar:Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _reset() {
    mrpBom = MrpBom();
    formKey.currentState!.reset();
    _loadData();
  }

  _loadData() async {
    var filter = {};
    if ((mrpBom.productName != null && mrpBom.productName != "")&&
        (mrpBom.productCode != null && mrpBom.productCode != "")) {
      filter = {
        "product.template": [
          'product_tmpl_id',
          ['name', 'like', '%${mrpBom.productName}%'],
          ['default_code', '=', mrpBom.productCode]
        ]
      };
    }else if(mrpBom.productName != null && mrpBom.productName != ""){
      filter = {
        "product.template": [
          'product_tmpl_id',
          ['name', 'like', '%${mrpBom.productName}%'],
        ]
      };
    }else if(mrpBom.productCode != null && mrpBom.productCode != ""){
      filter = {
        "product.template": [
          'product_tmpl_id',
          ['default_code', '=', mrpBom.productCode]
        ]
      };
    }
    ResponseBodyApi responseBodyApi = await MrpBomOdooApi.page(
        data:{"page": page,"domainList":mrpBom.toDomainList(),"filter":filter});
    if(responseBodyApi.success!){
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
    }
  }

  _sort(column, {ascending}) {
    page.orders[0].column = column;
    page.orders[0].asc = ascending ?? !page.orders[0].asc!;
    _query();
  }

  _getSelectList(){
    selectedList = tableKey.currentState
        ?.getSelectedList(page)
        .map<MrpBom>((e) => MrpBom.fromMap(e))
        .toList() ??
        [];
    setState(() { });
  }

  _save(MrpBom mrpBom) {
    //产品图号
    productionorder.productspec = mrpBom.productCode;
    //产品名称
    productionorder.productname = mrpBom.productName;
    //产品规格
    productionorder.productstyle = mrpBom.spec;
    //单位
    productionorder.unitname = mrpBom.uomName;
    ProductProductionorderOdooApi.saveOrUpdate(
        productionorder.toOdooMap())
        .then((ResponseBodyApi res) {
      if (!res.success!) {
        return;
      }
      Navigator.pop(context, true);
      CryUtils.message(S.of(context).saved);
    });
  }

}